// WebRTC client functionality for classroom component

class WebRTCClient {
  constructor(config) {
    this.config = config;
    this.peerConnection = null;
    this.localStream = null;
    this.remoteStream = null;
    this.isRecording = false;
  }

  async initialize(localVideoElement, remoteVideoElement) {
    try {
      // Get local media stream
      this.localStream = await navigator.mediaDevices.getUserMedia({
        video: true,
        audio: true
      });

      // Set local video stream
      if (localVideoElement) {
        localVideoElement.srcObject = this.localStream;
      }

      // Create peer connection
      this.createPeerConnection(remoteVideoElement);

      // Add local tracks to connection
      this.localStream.getTracks().forEach(track => {
        this.peerConnection.addTrack(track, this.localStream);
      });

      return true;
    } catch (error) {
      console.error('Error initializing WebRTC:', error);
      return false;
    }
  }

  createPeerConnection(remoteVideoElement) {
    const configuration = {
      iceServers: this.config.iceServers || [{ urls: 'stun:stun.l.google.com:19302' }]
    };

    this.peerConnection = new RTCPeerConnection(configuration);

    // Handle remote tracks
    this.peerConnection.addEventListener('track', (event) => {
      [this.remoteStream] = event.streams;
      if (remoteVideoElement) {
        remoteVideoElement.srcObject = this.remoteStream;
      }
    });

    // Handle ICE candidates
    this.peerConnection.addEventListener('icecandidate', (event) => {
      if (event.candidate) {
        // Send ICE candidate to remote peer via signaling server
        this.sendIceCandidate(event.candidate);
      }
    });

    // Handle connection state changes
    this.peerConnection.addEventListener('connectionstatechange', (event) => {
      console.log('Connection state changed:', this.peerConnection.connectionState);
    });
  }

  async createOffer() {
    if (!this.peerConnection) {
      throw new Error('Peer connection not initialized');
    }

    const offer = await this.peerConnection.createOffer({
      offerToReceiveAudio: true,
      offerToReceiveVideo: true
    });

    await this.peerConnection.setLocalDescription(offer);

    return offer;
  }

  async createAnswer(offer) {
    if (!this.peerConnection) {
      throw new Error('Peer connection not initialized');
    }

    await this.peerConnection.setRemoteDescription(offer);

    const answer = await this.peerConnection.createAnswer();
    await this.peerConnection.setLocalDescription(answer);

    return answer;
  }

  async setRemoteAnswer(answer) {
    if (!this.peerConnection) {
      throw new Error('Peer connection not initialized');
    }

    await this.peerConnection.setRemoteDescription(answer);
  }

  addRemoteIceCandidate(candidate) {
    if (!this.peerConnection) {
      throw new Error('Peer connection not initialized');
    }

    this.peerConnection.addIceCandidate(candidate);
  }

  sendIceCandidate(candidate) {
    // In a real implementation, this would send the candidate to the remote peer
    // via a WebSocket or other signaling mechanism
    console.log('Sending ICE candidate:', candidate);
  }

  toggleRecording() {
    this.isRecording = !this.isRecording;
    // In a real implementation, this would start/stop recording functionality
    console.log(this.isRecording ? 'Started recording' : 'Stopped recording');
    return this.isRecording;
  }

  async shareScreen() {
    try {
      // Get screen stream
      const screenStream = await navigator.mediaDevices.getDisplayMedia({ 
        video: true 
      });

      // Replace the current video track with the screen capture
      const videoTrack = screenStream.getVideoTracks()[0];
      const sender = this.peerConnection.getSenders().find(sender => 
        sender.track && sender.track.kind === 'video'
      );

      if (sender) {
        sender.replaceTrack(videoTrack);
      }

      // Listen for when the user stops sharing
      screenStream.getVideoTracks()[0].onended = () => {
        // Switch back to camera
        if (this.localStream) {
          const cameraTrack = this.localStream.getVideoTracks()[0];
          if (sender) {
            sender.replaceTrack(cameraTrack);
          }
        }
      };

      return screenStream;
    } catch (error) {
      console.error('Error sharing screen:', error);
      throw error;
    }
  }

  disconnect() {
    if (this.peerConnection) {
      this.peerConnection.close();
      this.peerConnection = null;
    }

    if (this.localStream) {
      this.localStream.getTracks().forEach(track => track.stop());
      this.localStream = null;
    }

    if (this.remoteStream) {
      this.remoteStream.getTracks().forEach(track => track.stop());
      this.remoteStream = null;
    }
  }
}

export default WebRTCClient;